/* globals Page */
import { ToastPannel } from './component/toast/toast'

App({
    ToastPannel,
    onLaunch: function (options) {
        const _this = this;
        if (options.query && options.query.channel) {
            _this.globalData.channel = options.query.channel;
        }
        if (options.query && options.query.appid) {
            _this.globalData.appid = options.query.appid;
        }
        // 展示本地存储能力
        // var logs = swan.getStorageSync('logs') || []
        // logs.unshift(Date.now())

        // 登录
        this.login(_this);
    },
    userInfoReadyCallback: (_this, res) => {
        if (_this.globalData.userid) {
            updateUserInfo(_this);
        }
        else {
            setTimeout(function () {
                updateUserInfo(_this);
            }, 10000);
        }
    },
    globalData: {
        platform: 'baidu',
        appid: '11699129',
        channel: '',
        userInfo: null,
        token: null,
        config: null,
        prefix: 'https://wz.whodear.com',
        // prefix: 'http://localhost:3001',
        tel: null,
    },
    onShow(event) {
        console.log('onShow');
    },
    login(_this) {
        swan.login({
            success: res => {
                _this.init(_this, res);
            },
            fail: err => {
                console.log(err);
                swan.showToast({
                    title: '登录失败'
                });
            }
        });
    },
    init(_this, res) {
        swan.request({
            url: `${_this.globalData.prefix}/api/login`,
            method: 'POST',
            header: {
                platform: _this.globalData.platform,
                channel: _this.globalData.channel || '',
                appid: _this.globalData.appid || ''
            },
            data: {
                code: res.code
            },
            success: function (ret) {
                console.log('login success')
                if (ret.data.status) {
                    _this.globalData.token = ret.data.token;
                    _this.globalData.userid = ret.data.userid;
                    _this.globalData.config = {
                        serviceFee: ret.data.serviceFee,//分
                        urgent: ret.data.urgent,//分
                        overdue: ret.data.overdue,//
                        overday: ret.data.overday,//
                        tel: ret.data.tel,
                        channel: ret.data.channel || _this.globalData.channel || '',
                        payType: ret.data.payType
                    }
                }
            },
            fail: function (ret) {
                console.log(ret);
            }
        },
        );
    }
});


